package com.lcj.aoch.rule.controller;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageInfo;
import com.lcj.aoch.rule.controller.form.DeleteRuleForm;
import com.lcj.aoch.rule.controller.form.InsertRuleForm;
import com.lcj.aoch.rule.controller.form.SearchRuleForm;
import com.lcj.aoch.rule.controller.form.UpdateRuleForm;
import com.lcj.aoch.rule.db.pojo.RuleEntity;
import com.lcj.aoch.rule.service.RuleService;
import com.lcj.common.util.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@RestController
@RequestMapping("/rule")
@Tag(name = "RuleManageController", description = "MIS系统规则管理接口")
public class RuleManageController {

    @Resource
    private RuleService ruleService;


    @PostMapping("/searchRule")
    public Result SearchRule(@RequestBody @Valid SearchRuleForm form) {
        form.setTable("tb_" + form.getTable() + "_rule");
        PageInfo ruleEntityPageInfo = ruleService.searchRule(form);
        RuleEntity currentRule = ruleService.searchCurrentRule(form);
        return Result.ok().put("result", ruleEntityPageInfo).put("current", currentRule);
    }

    @PostMapping("/insertRule")
    public Result insertRule(@RequestBody @Valid InsertRuleForm form) {
        form.setTable("tb_" + form.getTable() + "_rule");
        form.setCreateTime(new DateTime());
        long rows = ruleService.insertRule(form);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/updateRule")
    public Result updateRule(@RequestBody @Valid UpdateRuleForm form) {
        form.setTable("tb_" + form.getTable() + "_rule");
        if(StringUtils.isNotBlank(form.getRule())) {

            Base64.Encoder encoder = Base64.getEncoder();
            String base64Rule = encoder.encodeToString(form.getRule().getBytes(StandardCharsets.UTF_8));
        }
        long rows = ruleService.updateRule(form);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/deleteRule")
    public Result deleteRule(@RequestBody @Valid DeleteRuleForm form) {
        form.setTable("tb_" + form.getTable() + "_rule");
        long rows = ruleService.deleteRule(form);
        return Result.ok().put("rows", rows);
    }
}
